<template>
  <div>
    <el-button type="primary"
               icon="el-icon-plus"
               @click="addShowDialog">添加</el-button>
    <el-table :data="trademarkList"
              border
              style="width: 100%;margin:20px 0">
      <el-table-column prop="prop"
                       align="center"
                       type="index"
                       label="序号"
                       width="80">
      </el-table-column>
      <el-table-column prop="tmName"
                       label="品牌名称"
                       width="width">
      </el-table-column>
      <el-table-column prop="prop"
                       label="品牌LOGO"
                       width="width">
        <template slot-scope="{row,$index}">
          <img :src="row.logoUrl"
               style="width:80px;height:60px">
        </template>
      </el-table-column>
      <el-table-column prop="prop"
                       label="操作"
                       width="width">
        <template slot-scope="{row,$index}">
          <el-button type="warning"
                     size="mini"
                     @click="updata(row)">修改</el-button>
          <el-button type="danger"
                     size="mini"
                     @click="deletaTrademark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination style="text-align:center"
                   @current-change="getTrademarkList"
                   :current-page="page"
                   :page-sizes="[3, 7, 10]"
                   :page-size="limit"
                   @size-change="handleSizeChange"
                   layout="  prev, pager, next, jumper,->,sizes,total"
                   :total="total">
    </el-pagination>

    <!-- Form -->
    <!-- 弹出框 -->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'"
               :visible.sync="dialogFormVisible">
      <el-form style="width:80%"
               :model="tmForm"
               :rules="rules"
               ref="formName">
        <el-form-item label="品牌名称"
                      :label-width="'100px'"
                      prop="tmName">
          <el-input v-model="tmForm.tmName"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO"
                      :label-width="'100px'"
                      prop="logoUrl">
          <el-upload class="avatar-uploader"
                     action="/dev-api/admin/product/fileUpload"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl"
                 :src="tmForm.logoUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip"
                 class="el-upload__tip">只能上传jpg/png文件，且不超过2048kb</div>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="confirmUpdata">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Trademark',
  data () {
    return {
      page: 1,
      limit: 3,
      trademarkList: [],
      total: 0,
      dialogFormVisible: false,
      tmForm: {
        tmName: '',
        logoUrl: ''
      },
      //单一验证
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌LOGO', trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    this.getTrademarkList()
  },
  methods: {
    //请求数据
    async getTrademarkList (page = 1) {
      this.page = page
      try {
        const result = await this.$API.trademark.getPageList(this.page, this.limit)
        if (result.code === 200 || result.code === 20000) {
          this.trademarkList = result.data.records
          this.total = result.data.total
        }
      } catch (error) {

      }
    },

    //图片上传成功的回调
    handleAvatarSuccess (res, file) {
      this.tmForm.logoUrl = res.data
    },
    //图片上传之前的回调
    beforeAvatarUpload (file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGorPNG && isLt2M;
    },
    //切换每页数量
    handleSizeChange (size) {
      this.limit = size
      this.getTrademarkList()
    },
    //添加
    addShowDialog () {
      this.dialogFormVisible = true
      this.tmForm = {
        tmName: '',
        logoUrl: ''
      }
    },
    //修改
    updata (row) {
      this.dialogFormVisible = true
      this.tmForm = { ...row }
    },
    //点击确定  整体表单验证并发送请求添加或者修改
    confirmUpdata () {
      this.$refs.formName.validate(async (valid) => {
        if (valid) {
          let trademark = this.tmForm
          try {
            await this.$API.trademark.updateTrademark(trademark)
            this.dialogFormVisible = false
            this.$message.success(trademark.id ? '修改成功' : '添加成功')
            this.getTrademarkList(trademark.id ? this.page : 1)
          } catch (error) {
            this.dialogFormVisible = false
            this.$message.error(trademark.id ? '修改失败' : '添加失败')
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //删除
    deletaTrademark (row) {
      this.$confirm(`你确定删除${row.tmName}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          console.log('11111')
          await this.$API.trademark.delete(row.id)
          this.$message.success('删除品牌成功')
          this.getTrademarkList(this.trademarkList.length > 1 ? this.page : this.page - 1)
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }

}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

